package com.cloudtasks;

import android.os.AsyncTask;

import com.appspot.api.services.taskservice.Taskservice;
import com.appspot.api.services.taskservice.model.Task;
import com.google.api.client.extensions.android2.AndroidHttp;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.json.jackson.JacksonFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class AsyncFetchTask extends AsyncTask<Long, Void, List<Task>> {

    private final CloudTasksActivity activity;
    private boolean newTask = false;

    public AsyncFetchTask(CloudTasksActivity activity) {
        super();
        this.activity = activity;
    }

    @Override
    protected List<Task> doInBackground(Long... arguments) {
        List<Task> list = new ArrayList<Task>();

        String baseUrl = Util.getBaseUrl(activity) + "_ah/api/a5463920/v1/";
        Taskservice taskService = Taskservice.builder(
                AndroidHttp.newCompatibleTransport(), 
                    new JacksonFactory())
                    .setBaseUrl(new GenericUrl(baseUrl))
                    .build();
        try {
            list = taskService.listTask().execute().getItems();
        } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }

        return list;
    }

    @Override
    protected void onPostExecute(List<Task> result) {
    	if (newTask) {
    		activity.addTasks(result);
    	} else {
    		activity.setTasks(result);
    	}
    }
}
